package cn.qingyun.gis.modules.handle;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JsonbListMapTypeHandler implements TypeHandler<JsonNode> {
    private final ObjectMapper objectMapper = new ObjectMapper();


    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, JsonNode jsonNode, JdbcType jdbcType) {
        String jsonStr = objectMapper.writeValueAsString(jsonNode);
        preparedStatement.setString(i, jsonStr);
    }

    @Override
    public JsonNode getResult(ResultSet resultSet, String columnName) throws SQLException {
        String jsonStr = resultSet.getString(columnName);
        return parseJson(jsonStr);
    }

    @Override
    public JsonNode getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String jsonStr = resultSet.getString(columnIndex);
        return parseJson(jsonStr);
    }

    @Override
    public JsonNode getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String jsonStr = callableStatement.getString(columnIndex);
        return parseJson(jsonStr);
    }

    private JsonNode parseJson(String jsonStr) throws SQLException {
        if (jsonStr == null || jsonStr.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readTree(jsonStr);
        } catch (IOException e) {
            throw new SQLException("Failed to parse JSON string: " + jsonStr, e);
        }
    }
}
